package com.cloudkinto.controller.order;

import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.order.OrderYahooService;
import com.cloudkinto.service.order.vo.Export2ShipOrderReq;
import com.cloudkinto.service.order.vo.OrderRakutenSysTipsReq;
import com.cloudkinto.service.order.vo.yahoo.OrderShipStatusChangeReq;
import com.cloudkinto.service.order.vo.yahoo.OrderYahooDoPageEntity;
import com.cloudkinto.service.order.vo.yahoo.OrderYahooExcelReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author huajiyu
 * @since 2022-07-11
 */
@RestController
@Api(tags = "雅虎订单模块")
@RequestMapping("/api/admin/OrderYahoo")
public class OrderYahooController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderYahooController.class);

    @Autowired
    private OrderYahooService service;

    @GetMapping("/addInit")
    @UserSessionRequired
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit();
    }

    @PostMapping("")
    @UserSessionRequired
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId));
    }
    @UserSessionRequired
    @GetMapping("ordersyncInit")
    @ApiOperation(value = "同步订单初始化", notes = "同步订单初始化")
    public SingleResult ordersyncInit() {
        return SingleResult.success(service.ordersyncInit(getCurrentUserId(), getCompanyId()));
    }
    @UserSessionRequired
    @PostMapping("/sync")
    @ApiOperation(value = "同步", notes = "同步")
    public SingleResult sync(Long shopId, String startDate, String endDate) {
        Map map = new HashMap();
        map.put("orderTimeFrom", startDate);
        map.put("orderTimeTo", endDate);
        return SingleResult.success("同步成功", service.getYahooOrderList(shopId, map));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id);
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit();
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderYahooDoPageEntity.class)})
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    public PageResult listPage(String isSend, String orderStatus, String shopId, String current, String pageSize,
                               String dateStart, String dateEnd, String dateType, String payStatus,String shipStatus, String keyword,String companyId) {
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.isEmpty(isSend))
            map.put("isSend", isSend);
        if (!StringUtils.isEmpty(orderStatus))
            map.put("orderStatus", orderStatus);
        if (!StringUtils.isEmpty(payStatus))
            map.put("payStatus", payStatus);
        if (!StringUtils.isEmpty(shipStatus))
            map.put("shipStatus", shipStatus);
        if (!StringUtils.isEmpty(keyword))
            map.put("keyword", keyword);
        if (!StringUtils.isEmpty(companyId))
            map.put("companyId", companyId + "");
        if (!StringUtils.isEmpty(shopId)) {
            map.put("shopId", shopId);
        }
        map.put("current", current + "");
        map.put("pageSize", pageSize + "");
        map.put("dateStart", dateStart);
        map.put("dateEnd", dateEnd);
        map.put("dateType", dateType);
        return service.getListPage(map);
    }

    /**
     * 把乐天订单组合成发货单
     *
     * @param req
     * @return
     */
    @UserSessionRequired
    @PostMapping("export2ShipOrder")
    @ApiOperation(value = "发货", notes = "乐天订单发货")
    public SingleResult export2ShipOrder(@RequestBody Export2ShipOrderReq req) {
        Long companyId = getCompanyId();
        if (req.getIsSolo() == 0) {
            return service.queryOrder2SendOut(req.getOrderids(), getCurrentUserId(), false, companyId);
        } else if (req.getOrderids().length > 0) {
            return service.queryOrder2SendOutNoPackage(req.getOrderids()[0], getCurrentUserId(), false, companyId);
        }
        return SingleResult.failure("无数据");
    }

    @UserSessionRequired
    @PostMapping("sendOutMatch")
    @ApiOperation(value = "确定发货", notes = "确定发货")
    public SingleResult sendOutMatch(@RequestBody List<OrderOutputAddReq> orderOutputAddReqList) {
        Long companyId = getCompanyId();
        Long userId = getCurrentUserId();
        return service.sendOutMatch(orderOutputAddReqList, userId, companyId);
    }

    /**
     * 把设置订单已转发货
     *
     * @param orderids
     * @return
     */
    @UserSessionRequired
    @PostMapping("setOrderSend")
    @ApiOperation(value = "标记为发货", notes = "标记为发货")
    public SingleResult setOrderSend(@RequestBody Long[] orderids) {
        Long userId = getCurrentUserId();
        int count = service.setOrderSend(orderids, userId);
        if (count == orderids.length) {
            return SingleResult.success();
        } else {
            return SingleResult.failure(String.format("失败%d条", orderids.length - count));
        }
    }

    /**
     * 编辑系统备注
     *
     * @return
     */
    @UserSessionRequired
    @PostMapping("setOrderSysTips")
    @ApiOperation(value = "编辑系统备注", notes = "编辑系统备注")
    @CacheEvict(value = "rakutendetail", allEntries = true)
    public SingleResult setOrderSysTips(@RequestBody OrderRakutenSysTipsReq req) {
        boolean b = service.setOrderSysTips(req.getId(), req.getDesc(), getCompanyId());
        return SingleResult.success();
    }



    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderYahooExcelReq req, HttpServletResponse response) throws Exception {
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.isEmpty(req.getIsSend()))
            map.put("isSend", req.getIsSend());
        if (!StringUtils.isEmpty(req.getOrderStatus()))
            map.put("orderStatus", req.getOrderStatus());
        if (!StringUtils.isEmpty(req.getPayStatus()))
            map.put("payStatus", req.getPayStatus());
        if (!StringUtils.isEmpty(req.getKeyword()))
            map.put("keyword", req.getKeyword());
        if (!StringUtils.isEmpty(req.getShopId())) {
            map.put("shopId", req.getShopId());
        }
        map.put("dateStart", req.getDateStart());
        map.put("dateEnd", req.getDateEnd());
        map.put("dateType", req.getDateType());
        service.exportExcel(map, req, response);
    }

}

